<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Google 登录测试 - Strapi</title>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    <style>
      body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; margin: 24px; }
      h1 { font-size: 20px; margin-bottom: 12px; }
      .row { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 8px; }
      label { display: flex; align-items: center; gap: 8px; }
      input, select { padding: 6px 8px; border: 1px solid #ddd; border-radius: 6px; min-width: 280px; }
      button { padding: 8px 12px; border: 1px solid #ccc; border-radius: 6px; background: #f8f8f8; cursor: pointer; }
      button:disabled { opacity: 0.5; cursor: not-allowed; }
      #gButton { margin: 12px 0; }
      #output { white-space: pre-wrap; background: #111; color: #e6e6e6; padding: 12px; border-radius: 8px; min-height: 160px; }
      small { color: #666; }
    </style>
  </head>
  <body>
    <h1>Google 登录测试（Strapi）</h1>

    <div class="row">
      <label>
        Google Client ID
        <input id="clientId" placeholder="例如：1234567890-abcxyz.apps.googleusercontent.com" />
      </label>
      <label>
        Strapi 基础地址
        <input id="strapiUrl" value="http://localhost:1337" />
      </label>
    </div>

    <div class="row">
      <label>
        Strapi 端点路径
        <input id="endpointPath" value="/api/connect/google/callback" />
      </label>
      <label>
        请求方式
        <select id="requestMethod">
          <option value="get">GET（?access_token=ID_TOKEN）</option>
          <option value="post">POST（{ access_token: ID_TOKEN }）</option>
        </select>
      </label>
    </div>

    <div class="row">
      <button id="initBtn">初始化并显示登录按钮</button>
      <button id="copyBtn" disabled>复制 ID Token</button>
      <button id="sendBtn" disabled>发送到 Strapi</button>
    </div>

    <div id="gButton"></div>

    <small>
      说明：此页面使用 Google Identity Services（GIS）直接拿到 ID Token（JWT）。<br/>
      - 若你的 Strapi 插件提供 <code>GET /.../callback?access_token=</code> 或 <code>POST /.../callback</code> 接口，可直接发送测试。<br/>
      - 不同插件的回调路径可能不同，请根据你的插件文档调整上方“端点路径”和“请求方式”。
    </small>

    <h2>调试输出</h2>
    <pre id="output"></pre>

    <script>
      let idToken = null;

      function print(msg) {
        const out = document.getElementById('output');
        out.textContent += (typeof msg === 'string' ? msg : JSON.stringify(msg, null, 2)) + '\n';
        out.scrollTop = out.scrollHeight;
      }

      function initializeGoogle() {
        const clientId = document.getElementById('clientId').value.trim();
        if (!clientId) { alert('请输入 Google Client ID'); return; }

        try {
          google.accounts.id.initialize({
            client_id: clientId,
            callback: handleCredentialResponse,
            ux_mode: 'popup',
          });

          google.accounts.id.renderButton(
            document.getElementById('gButton'),
            { theme: 'outline', size: 'large', text: 'signin_with' }
          );

          print('已初始化，点击按钮进行 Google 登录。');
        } catch (e) {
          print('初始化失败：' + e.message);
        }
      }

      function handleCredentialResponse(response) {
        if (!response || !response.credential) { print('未获取到凭证'); return; }
        idToken = response.credential;
        document.getElementById('copyBtn').disabled = false;
        document.getElementById('sendBtn').disabled = false;

        print('获得 ID Token：' + idToken.slice(0, 60) + '...');
        try {
          const payloadPart = idToken.split('.')[1];
          const payload = JSON.parse(atob(payloadPart.replace(/-/g, '+').replace(/_/g, '/')));
          print('解码的用户信息：');
          print(payload);
        } catch (e) {
          print('解析 ID Token 失败：' + e.message);
        }
      }

      async function sendToStrapi() {
        if (!idToken) { alert('请先登录获取 ID Token'); return; }
        const base = document.getElementById('strapiUrl').value.replace(/\/+$/, '');
        const path = document.getElementById('endpointPath').value || '';
        const method = document.getElementById('requestMethod').value;

        const url = base + path + (method === 'get' ? ('?access_token=' + encodeURIComponent(idToken)) : '');
        print('请求：' + method.toUpperCase() + ' ' + url);

        try {
          const res = await fetch(url, {
            method: method === 'get' ? 'GET' : 'POST',
            headers: method === 'post' ? { 'Content-Type': 'application/json' } : {},
            body: method === 'post' ? JSON.stringify({ access_token: idToken }) : undefined,
            credentials: 'include',
          });
          const text = await res.text();
          print('状态：' + res.status);
          print('响应：\n' + text);
        } catch (err) {
          print('请求失败：' + err.message);
        }
      }

      function copyToken() {
        if (!idToken) { return; }
        navigator.clipboard.writeText(idToken)
          .then(() => print('已复制到剪贴板。'))
          .catch(e => print('复制失败：' + e.message));
      }

      document.getElementById('initBtn').addEventListener('click', initializeGoogle);
      document.getElementById('sendBtn').addEventListener('click', sendToStrapi);
      document.getElementById('copyBtn').addEventListener('click', copyToken);
    </script>
  </body>
</html>